var express = require('express');
var router = express.Router();
var Category = require('../models/category');
var multer  = require('multer');
var User = require('../models/user');
var Post = require('../models/post');
var Meta = require('../models/meta');
var Collect = require('../models/collect');
var mongoose = require('mongoose');


var pageHelper = require('../helper/page');
var checkLogin = require('../middlewares/check').checkLogin;

// 设置文件上传的存放目录及生成后的名字
var storage = multer.diskStorage({
  destination: function (req, file, cb) {
    console.log(file);
    cb(null, 'public/upload/')
  },
  filename: function (req, file, cb) {
    cb(null, file.fieldname + '-' + Date.now())
  }
})
// 将multer配置赋值
var upload = multer({ storage: storage })


// GET /posts 文章页
router.get('/', function(req, res, next) {
  res.render('posts', {
    title: '列表',
  });
});

// POST 获取各种类型的数据
router.get('/type/:slug', function(req, res, next) {
  var slug =  req.params.slug;
  if (!slug) return next(err);
  // 获取传递page
  var page = req.query.page || 1;
  pageHelper.pageQuery(page,6,Post,['category','author'],{"category_slug": slug},{created: 'desc'}, function (err, $page){
    if (err) {
      return next(err);
    } else {
      res.jsonp($page);
    }
  });
});

// GET 获取用户的数据
router.get('/user/:userid', function(req, res, next) {
  var userid =  req.params.userid;
  if (!userid) return next(err);
  // 获取传递page
  var page = req.query.page || 1;
  pageHelper.pageQuery(page,6,Post,['category','author'],'',{created: 'desc'}, function (err, $page){
    if (err) {
      return next(err);
    } else {
      res.jsonp($page);
    }
  });
});


// GET  /article/add/:type 添加文章
router.get('/add/:type', function(req, res, next) {
  var slug = req.params.type;
  if (!slug) return next(err); 
  // 根据slug 获得分类信息 
  Category.getCategory(slug, function (err, result) {
    if (err) return next(err);
    res.render('release', {
      title: '发布'+result.name,
      category: result
    });
  });
});



// POST /article/add:type 添加文章
router.post('/add', upload.array('photo', 3), function(req, res, next){
    var title         = req.body.title,
        body          = req.body.body,
        area          = req.body.area || '',
        category      = req.body.category,
        category_slug = req.body.category_slug,
        photo         = req.files || [],
        contact_name  = req.body.contact_name || '',
        contact_phone = req.body.contact_phone || '';

    var userId = req.session.user._id;
    if (userId) {
      User.findOne({'_id': userId}, function (err, author) {
        if (err) return next(err);
        var post =  new Post({
          'authorId'      : userId,
          'title'         : title,
          'body'          : body,
          'area'          : area,
          'category'      : category,
          'category_slug' : category_slug,
          'author'        : author,
          'photo'         : photo,
          'contact_name'  : contact_name,
          'contact_phone' : contact_phone,
          'skim_num'      : 0,
          'comments'      : [],
          'top'           : false,
          'topTime'       : '',
          'elite'         : false,
          'created_at'       : new Date()
        });
        // 保存文章
        var promise = post.save();
        // 保存成功
        promise.then(function (post) {
          req.flash('success', '发布成功！');
          res.redirect('/article');
        })
        // 保存失败
        .catch(function (err) {
          req.flash('success', '发布失败, 请联系管理员！');
          res.redirect('/article');
        });
      });
    } else {
      if (err) return next(new Error('请返回到公众号入口重新授权！'));
    }



    // req.checkBody('title', '标题格式不正确').notEmpty();
    // req.checkBody('body', '内容不能为空').notEmpty();
    // req.checkBody('contact_name', '联系人不能为空').notEmpty();
    // req.checkBody('contact_phone', '联系人手机格式不正确').notEmpty().isInt();
    // req.checkBody('area', '地区不能为空').notEmpty();

    // console.log('文件类型：%s', files.mimetype);
    // console.log('原始文件名：%s', files.originalname);
    // console.log('文件大小：%s', files.size);
    // console.log('文件保存路径：%s', files.path)
});

// GET /article/:postId 文章详情  浏览量+1
router.get('/:postId', function(req, res, next) {
  var id = req.params.postId;
  if (!id) return next(err);
  Post.findOne({'_id': id}).populate('category').populate('author').exec(function (err, post) {
    if (err) return next(err);
    // 为了浏览量自增1所以重新保存
    post.skim_num = post.skim_num+=1;
    post.markModified('skim_num');
    post.save(function (err, post) {
      res.render('detail', {
        'title': '文章详情',
        'article': post
      });
    });
  });
});

// POST /article/:postId/comment 创建一条留言
router.post('/:postId/comment', function(req, res, next) {
  Post.findOne({_id: req.params.postId}).exec(function (err, post) {
    if (err) return next(err);
    console.log(post);
    var comment = {
        "userid": req.body.userid,
        "username": req.body.username,
        "userheadimgurl": req.body.userheadimgurl,
        "body": req.body.body,
        "reply": [],
        "created_at": new Date()
    };
    post.comments.unshift(comment);
    post.markModified('comments');
    post.save(function (err, post) {
      var comments_len = post.comments.length;
      res.jsonp({'result':0, 'comment': comment, 'comments_len': comments_len})
    });
  });
});



// GET /article/:postId/metas  查看当前文章一共有多少赞
router.get('/:postId/metas', function(req, res, next) {
  var postId = req.params.postId;
  if (!postId) return next(new Error('no postId in app'));
  Meta.find({post:postId}).exec(function(err, meta){
    if (err) return next(err);
    res.jsonp({'count': meta.length});
  });
});

// GET /article/:postId/meta/get  查看当前用户是否已点过赞
router.get('/:postId/meta/get', function(req, res, next) {
  var postId = req.params.postId;
  if (!postId) return next(new Error('no postId in app'));
  // 查询用户是否点过赞
  Meta.findOne({userid: req.session.user._id, post: postId}, function(err, meta) {
    if (err) return next(err);
    // 当前用户针对当前文章还没有点过赞
    if (meta == null) {
      res.jsonp({'result': 0, 'meta': meta});
    } else {
      // 当前用户针对当前文章已经点过赞
      res.jsonp({'result': 1, 'meta': meta});
    }
  });
});

// GET /article/:postId/meta/add  针对当前文章点赞
router.get('/:postId/meta/add', function(req, res, next) {
  var postId = req.params.postId;
  if (!postId) return next(new Error('no postId in app'));

  var meta = new Meta({
    'userid': req.session.user._id,
    'post': postId,
    'create_at': new Date()
  });
  // 保存点赞
  var promise = meta.save();
  promise.then(function (meta) {
    // 保存成功
    res.jsonp({'result':1, 'meta': meta});
  })
  .catch(function (err) {
    if (err) return next(err);
  });
});

// GET /article/:postId/meta/del  针对当前文章取消点赞
router.get('/:metaId/meta/del', function(req, res, next) {
  var metaId = req.params.metaId;
  if (!metaId) return next(new Error('no metaId in app'));
  Meta.remove({_id: metaId}, function (err) {
    if (err) return next(err);
    res.jsonp({'result':1});
  });
});



// GET /article/:postId/collects  查看当前文章一共有多少收藏
router.get('/:postId/collects', function(req, res, next) {
  var postId = req.params.postId;
  if (!postId) return next(new Error('no postId in app'));
  Collect.find({post:postId}).exec(function(err, collect){
    if (err) return next(err);
    res.jsonp({'count': collect.length});
  });
});

// GET /article/:postId/collect/get  查看当前用户是否已收藏
router.get('/:postId/collect/get', function(req, res, next) {
  var postId = req.params.postId;
  if (!postId) return next(new Error('no postId in app'));
  // 查询用户是否收藏
  Collect.findOne({userid: req.session.user._id, post: postId}, function (err, collect) {
    if (err) return next(err);
    // 当前用户针对当前文章还没有收藏
    if (collect == null) {
      res.jsonp({'result': 0, 'collect': collect});
    } else {
      // 当前用户针对当前文章已经收藏
      res.jsonp({'result': 1, 'collect': collect});
    }
  });
});

// GET /article/:postId/collect/add  针对当前文章新增收藏
router.get('/:postId/collect/add', function (req, res, next) { 
  var postId = req.params.postId;
  if (!postId) return next(new Error('no postId in app'));
  var collect =  new Collect({
    'userid': req.session.user._id,
    'post': postId,
    'create_at': new Date()
  });
  // 保存新增
  var promise = collect.save();
  promise.then(function (collect) {
    // 收藏成功
    res.jsonp({'result':1, 'collect':collect});
  })
  .catch(function (err) {
    if (err) return next(err);
  });
});


// GET /article/:postId/collect/del  针对当前文章取消收藏
router.get('/:collectId/collect/del', function(req, res, next) {
  var collectId = req.params.collectId;
  if (!collectId) return next(new Error('no collectId in app'));
  Collect.remove({_id: collectId}, function (err) {
    if (err) return next(err);
    // 取消收藏成功
    res.jsonp({'result':1});
  });
});



// GET /posts/:postId/comment/:commentId/remove 删除一条留言
router.get('/:postId/comment/:commentId/remove', checkLogin, function(req, res, next) {
  res.send(req.flash());
});


module.exports = router;